/* eslint no-console:0 */
import React, {useEffect, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import {AndroidOutlined, AppleOutlined,} from '@ant-design/icons';
import {Card, Alert, Typography, UploadProps, Menu, Tabs} from 'antd';
import {useIntl, FormattedMessage} from 'umi';
import {Map, Marker} from 'react-amap';
import styles from './Welcome.less';
// import {Editor} from 'react-draft-wysiwyg';
// import '../../node_modules/react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
// // 引入draft-js
// import {convertToRaw, EditorState} from 'draft-js';
// // 引入draft-to-html
// import draftToHtml from 'draftjs-to-html';

import '@wangeditor/editor/dist/css/style.css'; // 引入 css

import {IDomEditor, IEditorConfig, IToolbarConfig} from '@wangeditor/editor';
import {upload} from '@/services/ant-design-pro/api';

import OSS from '../aliyun-upload-sdk/lib/aliyun-oss-sdk-6.17.1.min.js';

// @ts-ignore
window.OSS = OSS;
import '../aliyun-upload-sdk/aliyun-upload-sdk-1.5.3.min.js';
import {UploadFile} from 'antd/es/upload/interface';
import CheckModule from '@/components/CheckModule';

const {TabPane} = Tabs;

const isDev = process.env.NODE_ENV === 'development';

const CodePreview: React.FC = ({children}) => (
  <pre className={styles.pre}>
    <code>
      <Typography.Text copyable>{children}</Typography.Text>
    </code>
  </pre>
);

const Welcome: React.FC = () => {
  const intl = useIntl();
  const [geocoder, setGeocoder] = useState<any>();
  const [regeocode, setRegeocode] = useState<any>();
  const [clickPoi, setSlickPoi] = useState<any>({
    longitude: 113.752934,
    latitude: 34.767007,
  });

  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [uploading, setUploading] = useState(false);

  const props: UploadProps = {
    multiple: false,
    maxCount: 1,
    // onChange(info) {
    //   console.log(info);
    //   if (info.file.status !== 'uploading') {
    //     console.log(info.file, info.fileList);
    //   }
    //   if (info.file.status === 'done') {
    //     message.success(`${info.file.name} file uploaded successfully`);
    //   } else if (info.file.status === 'error') {
    //     message.error(`${info.file.name} file upload failed.`);
    //   }
    // },
    customRequest: ({file, onSuccess, onProgress, onError}) => {
      console.log(file, "dddddddddd")
      // @ts-ignore
      const uploader = new AliyunUpload.Vod({
        //userID，必填，您可以使用阿里云账号访问账号中心（https://account.console.aliyun.com/），即可查看账号ID
        userId: '1378061344581407',
        //分片大小默认1 MB，不能小于100 KB（100*1024）
        partSize: 1048576,
        //并行上传分片个数，默认5
        parallel: 5,
        //网络原因失败时，重新上传次数，默认为3
        retryCount: 3,
        //网络原因失败时，重新上传间隔时间，默认为2秒
        retryDuration: 2,
        //开始上传
        onUploadstarted: (uploadInfo) => {
          console.log(uploadInfo);
          let UploadAuth =
            'eyJTZWN1cml0eVRva2VuIjoiQ0FJU3lRVjFxNkZ0NUIyeWZTaklyNWZFQ2NMRW5lWlY5UGZlYUhMUzBHa2xaTnRFdmF6TTFEejJJSDFFZm5sb0FPa2FzUHd6bFd0UjZmd2VsclVxRU1BVkhSS2ROcGNzczhRT3JWditKcGZadjh1ODRZQURpNUNqUWU4RHc5OVZoSjI4V2Y3d2FmK0FVQnpCQ1RtZDVMb1lvOWJUY1RHbFFDWVBXLy90b0pWN2I5TVJjeENsWkQ1ZGZybC9MUmRqcjhsbzlCR3pVUEcyS1V6U24zYjNCa2hsc1JZZTcyUms4dmFIeGRhQXpSRGNnVmJtcUlrU3ZKK2pDWis4ZnU1bVBwcDBUN1hRMi9kdEpJWE16QWxhNlJWQjZNVU9pN2RmcXg3ZnB0eWJEMzViNFJpTkw0aXk5Y1owZmk5MGI2UWRFYXhKcCtTZTdQcGpvYjc4bXBqUXdSUkFOdjF3WGpqV0p2T24yOUNXT2VXb0t0Y3dhYnZlSm5EUjA4aUdMSVhJcXdjamFINTVUd1JSWUlnRU4zdHNDQVFsVUMzbk1xdWc4VnlvQkFDNFVQcTR5S1V4MkpaTnhrLzBuNkNOUEVQZGZxMmQxaThVQXBZbWMyZ3ZMdzkwcm12NmFmMHRkQWxVZDE1N0NwT0lTWmx5ZEJsRXRaN3d1UXJiV2s4UXlXcE03ZFQwWU9uS243MGJkWVRu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hbmdoYWkifQ==';
          let UploadAddress =
            'eyJFbmRwb2ludCI6Imh0dHBzOi8vb3NzLWNuLWJlaWppbmcuYWxpeXVuY3MuY29tIiwiQnVja2V0Ijoib3V0aW4tMWJkY2YwN2Q0ZTNjMTFlYWFjNmEwMDE2M2UxYzkyNTYiLCJGaWxlTmFtZSI6ImN1c3RvbWVyVHJhbnMvMWJlZjhkYTFlYjVkMTRjYTYwYzY5NjE1YjdmODMxZTUvNDAyNGM5ZDAtMTg0NjRmMTRkZGQtMDAwNC1lNTU2LWU4ZS1jMjcxZi5tcDQifQ==';
          let VideoId = '1e0f0a1ef9b54a719ad520d4c4e36466';
          // UploadAuth = '';

          uploader.setUploadAuthAndAddress(uploadInfo, UploadAuth, UploadAddress, VideoId);
        },
        //文件上传成功
        onUploadSucceed: function (uploadInfo: any) {
          uploader.stopUpload();
          onError(new Error('onUploadTokenExpired'));
          // console.log('onUploadSucceed', uploadInfo);
          onSuccess('done');
        },
        //文件上传失败
        onUploadFailed: function (uploadInfo, code, message) {
          onError(new Error(message));
        },
        //文件上传进度，单位：字节
        onUploadProgress: function (uploadInfo, totalSize, loadedPercent) {
          let percent = Math.round(loadedPercent * 100);
          onProgress({percent}, file);
          console.log('onUploadProgress', uploadInfo, totalSize, percent);
        },
        //上传凭证或STS token超时
        onUploadTokenExpired: function (uploadInfo) {
          onError(new Error('上传凭证或STS token超时'));
          console.log('onUploadTokenExpired', uploadInfo);
        },
        //全部文件上传结束
        onUploadEnd: function (uploadInfo) {
          console.log('onUploadEnd', uploadInfo);
        },
      });
      if (uploader) {
        uploader.stopUpload();
      }
      console.log(onProgress);
      uploader.addFile(file, null, null, null, '{"Vod":{}}');
      uploader.startUpload();
    },
  };

  // 定义高德地图插件
  const plugins = [
    // 'MapType',
    'Scale',
    // 'OverView',
    // 'ControlBar',
    {
      name: 'ToolBar',
      options: {
        visible: true,
        onCreated(ins: any) {
          console.log(ins);
        },
      },
    },
  ];
  const events = {
    created: (map: any) => {
      map.plugin(['AMap.Geocoder'], () => {
        // @ts-ignore
        let geocoder1 = new window.AMap.Geocoder();
        setGeocoder(geocoder1);
      });
    },
    click: (a: any) => {
      geocoder.getAddress([a.lnglat.lng, a.lnglat.lat], function (status: any, result: any) {
        if (status === 'complete' && result.regeocode) {
          setRegeocode(result.regeocode);
        } else {
          console.log('根据经纬度查询地址失败');
        }
      });
      console.log(geocoder);
      setSlickPoi({
        longitude: a.lnglat.lng,
        latitude: a.lnglat.lat,
      });
    },
  };

  const ZoomCtrl = (props: any) => {
    const map = props.__map__;
    if (!map) {
      console.log('组件必须作为 Map 的子组件使用');
      return <></>;
    }
    const style = {
      position: 'absolute',
      top: '10px',
      left: '10px',
      background: '#fff',
      padding: '10px',
    };
    // const zoomIn = () => map.zoomIn();
    // const zoomOut = () => map.zoomOut();

    if (regeocode) {
      // @ts-ignore
      return <div style={style}>{regeocode && regeocode.formattedAddress}</div>;
    }
    return <></>;
  };
  // editor 实例
  const [editor, setEditor] = useState<IDomEditor | null>(null); // TS 语法
  // 编辑器内容
  const [html, setHtml] = useState('');
  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {}; // TS 语法
  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    // TS 语法
    placeholder: '请输入内容...',
    MENU_CONF: {
      uploadImage: {
        // 自定义上传
        customUpload: async function (file: File, insertFn: any) {
          // TS 语法
          console.log(file);
          upload(file).then((value) => {
            console.log(value);
            // @ts-ignore
            insertFn(value.data.url, value.data.alt, value.data.href);
          });

          // async customUpload(file, insertFn) {                   // JS 语法
          // file 即选中的文件
          // 自己实现上传，并得到图片 url alt href
          // 最后插入图片
        },
        // withCredentials: true,
        // server: 'http://localhost:8080/enterprise/editor/upload',
        // fieldName: 'file',
        // header: {
        //   Authorization: `Bearer ${localStorage.getItem('token')}`
        // }
      },
    },
  };
  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  // const access = useAccess(); // access 实例的成员: canReadFoo, canUpdateFoo, canDeleteFoo
  //
  // // const {initialState} = useModel('@@initialState');
  // if (!access.isApprove) {
  //   notification.warn({
  //     message: "账号未认证",
  //     description: '您的账号还没有认证,请先申请企业信息认证。如已申请,请等待认证通过!',
  //   });
  //   history.push("/account/approve");
  //   // 任意操作
  // }
  const tabList = [
    {
      key: 'tab1',
      tab: <span><AndroidOutlined/>安卓APP下载</span>,
    },
    {
      key: 'tab2',
      tab: <span><AppleOutlined/>苹果APP下载</span>,
    },
  ];
  const contentList: Record<string, React.ReactNode> = {
    tab1: <div style={{textAlign: 'center', padding: '15px'}}>
      <div>请使用浏览器扫码下载，微信直接点击右上角，在浏览器中打开</div>
      <img alt="logo" src="/android.png" style={{width: '280px'}}/>
    </div>,
    tab2: <div style={{textAlign: 'center', padding: '15px'}}>
      <div>请使用浏览器扫码下载，微信直接点击右上角，在浏览器中打开</div>
      <img alt="logo" src="/apple.png" style={{width: '280px'}}/>
    </div>,
  };
  const [activeTabKey1, setActiveTabKey1] = useState<string>('tab1');
  const onTab1Change = (key: string) => {
    setActiveTabKey1(key);
  };
  return (
    <CheckModule code={''}>
      <PageContainer>
        <Card
          // className={styles.tabs}
          // style={{width: "500px"}}
          title=""
          tabList={tabList}
          activeTabKey={activeTabKey1}
          onTabChange={key => {
            onTab1Change(key);
          }}
        >
          {contentList[activeTabKey1]}
        </Card>
        {isDev ? (
          <>
            {/*<HeaderDropdown overlay={menuHeaderDropdown}>*/}
            {/*  <Button>hover 展示菜单</Button>*/}
            {/*</HeaderDropdown>*/}
            {/*<Upload {...props}>*/}
            {/*  <Button icon={<UploadOutlined />}>Select File</Button>*/}
            {/*</Upload>*/}
            {/*<Access*/}
            {/*  // @ts-ignore*/}
            {/*  accessible={access.canAdmin}*/}
            {/*  fallback={<div>Can not read foo content.</div>}>*/}
            {/*  Foo content.*/}
            {/*</Access>*/}
            {/*<>*/}
            {/*  <div style={{ border: '1px solid #ccc', zIndex: 100 }}>*/}
            {/*    <Toolbar*/}
            {/*      editor={editor}*/}
            {/*      defaultConfig={toolbarConfig}*/}
            {/*      mode="simple"*/}
            {/*      style={{ borderBottom: '1px solid #ccc' }}*/}
            {/*    />*/}
            {/*    <Editor*/}
            {/*      defaultConfig={editorConfig}*/}
            {/*      value={html}*/}
            {/*      onCreated={setEditor}*/}
            {/*      onChange={(editor) => setHtml(editor.getHtml())}*/}
            {/*      mode="default"*/}
            {/*      style={{ height: '500px', overflowY: 'hidden' }}*/}
            {/*    />*/}
            {/*  </div>*/}
            {/*  <div style={{ marginTop: '15px' }}>{html}</div>*/}
            {/*</>*/}
            <Card>
              <Alert
                message={intl.formatMessage({
                  id: 'pages.welcome.alertMessage',
                  defaultMessage: 'Faster and stronger heavy-duty components have been released.',
                })}
                type="success"
                showIcon
                banner
                style={{
                  margin: -12,
                  marginBottom: 24,
                }}
              />
              <Typography.Text strong>
                <FormattedMessage
                  id="pages.welcome.advancedComponent"
                  defaultMessage="Advanced Form"
                />{' '}
                <a
                  href="https://procomponents.ant.design/components/table"
                  rel="noopener noreferrer"
                  target="__blank"
                >
                  <FormattedMessage id="pages.welcome.link" defaultMessage="Welcome"/>
                </a>
              </Typography.Text>
              <CodePreview>yarn add @ant-design/pro-table</CodePreview>
              <Typography.Text
                strong
                style={{
                  marginBottom: 12,
                }}
              >
                <FormattedMessage
                  id="pages.welcome.advancedLayout"
                  defaultMessage="Advanced layout"
                />{' '}
                <a
                  href="https://procomponents.ant.design/components/layout"
                  rel="noopener noreferrer"
                  target="__blank"
                >
                  <FormattedMessage id="pages.welcome.link" defaultMessage="Welcome"/>
                </a>
              </Typography.Text>
              <CodePreview>yarn add @ant-design/pro-layout</CodePreview>
            </Card>
            <div className="map-container">
              <h1 className="item">React-高德地图的简单应用</h1>
              <div
                className="map"
                style={{width: '800px', height: '500px', background: '#d54242'}}
              >
                <Map
                  useAMapUI
                  amapkey={"2c6174f482ae27c8674c3b60476955e0"}
                  // @ts-ignore
                  plugins={plugins}
                  zoom={16}
                  center={[113.752934, 34.767007]}
                  events={events}
                  loading={<div>Loading Map...</div>}
                >
                  <Marker position={clickPoi}/>
                  <ZoomCtrl/>
                </Map>
              </div>
            </div>
          </>
        ) : (
          <></>
        )}
      </PageContainer>
    </CheckModule>
  );
};

export default Welcome;
